package rjeutsky.xml.sax;

import java.util.LinkedList;
import java.util.List;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.helpers.DefaultHandler;

import rjeutsky.models.CardThema;
import rjeutsky.models.CardType;
import rjeutsky.models.OldCard;
import rjeutsky.models.TypeEnum;
import rjeutsky.models.builders.ConcreteOldCardBuilder;
import rjeutsky.xml.common.TagNames;

public class OldCardSaxParser extends DefaultHandler {
	private List<OldCard> cards;
	private ConcreteOldCardBuilder builder;
	private CardType cardType;
	private String text;
	
	
	@Override
	public void startDocument() throws SAXException {
		cards = new LinkedList<OldCard>();
		super.startDocument();
	}

	@Override
	public void endDocument() throws SAXException {
	}

	@Override
	public void startElement(String uri, String localName, String qName,
			Attributes attributes) throws SAXException {
		text = null;
		if (qName.equals(TagNames.OLD_CARD)) {
			builder = new ConcreteOldCardBuilder();
		} else if (qName.equals(TagNames.CARD_TYPE)) {
			cardType = new CardType();
			cardType.setIsSent(Boolean.parseBoolean(attributes.getValue(TagNames.IS_SEND)));
		}
	}

	@Override
	public void endElement(String uri, String localName, String qName)
			throws SAXException {
		if (qName.equals(TagNames.OLD_CARD)) {
			builder.createNewCard();
			builder.buildAll();
			cards.add(builder.getCard());
		} else if (qName.equals(TagNames.CARD_TYPE)) {
			cardType.setType(TypeEnum.valueOf(text));
			builder.setType(cardType);
		} else if (qName.equals(TagNames.THEMA)) {
			builder.setThema(CardThema.valueOf(text));
		} else if (qName.equals(TagNames.COUNTRY)) {
			builder.setCountry(text);
		} else if (qName.equals(TagNames.YEAR)) {
			builder.setYear(Integer.parseInt(text));
		} else if (qName.equals(TagNames.AUTHOR)) {
			builder.setAuthor(text);
		} else if (qName.equals(TagNames.VALUABLE)) {
			builder.setValuable(text);
		}
	}

	@Override
	public void characters(char[] ch, int start, int length)
			throws SAXException {
		text = new String(ch, start, length);
	}

	@Override
	public void error(SAXParseException e) throws SAXException {
		throw new SAXException(e);
	}

	@Override
	public void fatalError(SAXParseException e) throws SAXException {
		throw new SAXException(e);
	}

	@Override
	public void warning(SAXParseException e) throws SAXException {
		throw new SAXException(e);
	}
	
	public List<OldCard> getCards() {
		return cards;
	}

}
